package com.guard.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class GuardWebViewClient extends WebViewClient {
    protected static final String TAG = WebViewClient.class.getName();
    protected Activity mActivity;

    public GuardWebViewClient(Activity webViewActivity) {
        mActivity = webViewActivity;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        String message = description;

        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != mActivity) {
                    mActivity.finish();
                }
                dialog.cancel();
            }
        };
        final Dialog dialog = createDialog(mActivity, message, listener);
        dialog.show();
    }

    private Dialog createDialog(Context context, String msg, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        DialogInterface.OnClickListener onClickListener = listener != null ? listener : new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        };
        builder.setMessage(msg).setCancelable(false).setPositiveButton(android.R.string.ok, onClickListener);

        AlertDialog alert = builder.create();
        return alert;
    }

}
